package com.smartthinking.CICPNL.home.activity;


import java.util.ArrayList;
import java.util.Dictionary;
import java.util.Hashtable;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

import com.smartthinking.CICPNL.R;
import com.smartthinking.CICPNL.R.id;
import com.smartthinking.CICPNL.home.objects.App_ImageLoader;

public class Expositores extends Activity {
	public static ArrayList<Dictionary> Actividades = null;
	private Dictionary dic;
	public ListView list;
	
	public Dialog progressDialog;
	public App_ImageLoader imageLoader;
	private Intent intent;
	public static ArrayList<Dictionary<String,String>> TraeDatos = null;
	public static ArrayList<Dictionary<String,String>> TraeDatos2 = null;
	public static ArrayList<Dictionary<String,String>> Banners = null;
	public static ArrayList<Dictionary<String,String>> Splash = null;
	public Integer EVEIDR;
	public TextView txtbusqueda;
	private boolean favoritos = false;
	Utilities util;
	String busqueda = "";
	boolean inicial = true;
	
	public void voidFinish(View V) {
		finish();
	}

	public void abrirMenuLateral(View V) {
		intent = new Intent(Expositores.this, MenuLateral.class);
		startActivity(intent);
	}

	@Override
	public void onBackPressed() {
	}
	
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		// Checks the orientation of the screen
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.ui_listview_expositores);
		util = new Utilities();
		
		getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
		TextView Titulo = (TextView) this.findViewById(id.tv_listView_Titulo);
		Titulo.setText(getString(R.string.modulo_expositores));
		EVEIDR = Utilities.EVE_IDR;
		
		EditText txtbusc = (EditText) Expositores.this.findViewById(id.et_buscar_buscar);
		txtbusc.setOnEditorActionListener(new OnEditorActionListener() {
		    @Override
		    public boolean onEditorAction(TextView v, int keyCode, KeyEvent event) {
		    	if (event != null&& (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
		    		InputMethodManager in = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		    		in.hideSoftInputFromWindow(v.getApplicationWindowToken(),InputMethodManager.HIDE_NOT_ALWAYS);
			        buscar();
			        return true;
		        }
		        return false;
		    }
		});
		
		CargarContenido();
	}

	private void CargarContenido() {
		new AsyncContenido().execute("");
	}
	
	private class AsyncContenido extends AsyncTask<String, String, String>{
		
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			progressDialog = ProgressDialog.show(Expositores.this, "",getResources().getString(R.string.msg_cargando));
		}

		@Override
		protected String doInBackground(String... params) {
		    String strBusqueda = ((EditText) Expositores.this.findViewById(id.et_buscar_buscar)).getText().toString().trim();
		    busqueda = strBusqueda;
		    
		    String strFavoritos = "";
		    if (favoritos) {
		        strFavoritos =util.getFavoritos(Expositores.this,"EXPOSITOR");
		        if (strFavoritos.length()>0) {
		            strFavoritos = "and exp_idr in("+strFavoritos+")";
		        }else{
		            strFavoritos = "and exp_idr in(9999999)";
		        }
		    }
			
			String qry =  "";
		    if (strBusqueda.length()>0) {
		    	qry = "select * from expositores where eve_idr = "+EVEIDR+" and (upper(exp_nombre) like upper('%%"+strBusqueda+"%%') or upper(exp_descripcion) like upper('%%"+strBusqueda+"%%') or upper(exp_descripcion_en) like upper('%%"+strBusqueda+"%%') or upper(exp_categoria) like upper('%%"+strBusqueda+"%%') or upper(exp_categoria_en) like upper('%%"+strBusqueda+"%%')) "+strFavoritos+" order by exp_nombre";
		    } else {
		    	qry = "select * from expositores where eve_idr = "+EVEIDR+" "+strFavoritos+" order by exp_nombre";
		    }
			TraeDatos2 = Utilities.qry2(getApplicationContext(), qry);
			
			//BANNERS Y SPLASH
			if(inicial){
				qry = "select a.* from eventos_banners a inner join banners_catalogo b on a.ban_idr = b.ban_idr where a.eve_idr = "+EVEIDR+" and b.ban_nombre in ('BANNER EXPOSITORES 1','BANNER EXPOSITORES 2','BANNER EXPOSITORES 3') ORDER BY b.ban_nombre";
				Banners = Utilities.qry2(getApplicationContext(), qry);
				
				qry = "select a.* from eventos_banners a inner join banners_catalogo b on a.ban_idr = b.ban_idr where a.eve_idr = "+EVEIDR+" and b.ban_nombre = 'SPLASH EXPOSITORES' ORDER BY b.ban_nombre";
				Splash = Utilities.qry2(getApplicationContext(), qry);
			}
			return null;
		}
		
		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			
			//acomodo banners
			TraeDatos = new ArrayList<Dictionary<String,String>>();
			Dictionary<String, String> dic = null;
			String encabezado = "";
			int intRenglon = 0;
			int intBanner = 0;
		    for (int i=0; i<TraeDatos2.size(); i++) {
		    	String strLetra = TraeDatos2.get(i).get("exp_nombre").toString().substring(0,1);
		    	if(!encabezado.equals(strLetra)){
		    		encabezado = strLetra;
		    		dic = new Hashtable<String, String>();
				    dic.put("Header", encabezado);
				    TraeDatos.add(dic);
		    	}
		    	TraeDatos.add(TraeDatos2.get(i));
		        
		        if (Banners.size()>0) {
		            if (intRenglon==0) {
		                TraeDatos.add(Banners.get(intBanner));
		                if (intBanner==0) {
		                    if (Banners.size()>1) {intBanner++;}else{intBanner=0;}
		                } else if (intBanner==1) {
		                    if (Banners.size()>2) {intBanner++;}else{intBanner=0;}
		                } else if (intBanner==2) {
		                    intBanner=0;
		                }
		            }
		        }
		        if (intRenglon==2) {intRenglon=0;} else {intRenglon++;}
		    }
		    
		    progressDialog.dismiss();
		    
		    //presento splash
		    if(inicial){
		    	inicial = false;
		    	if(Splash.size()>0){
			    	dic = Splash.get(0);
			    	String strPoster = dic.get("ban_url").toString();
				    String strTimer = dic.get("ban_timer").toString();
				    String strPatrocinador = dic.get("pat_idr").toString();
				    if (strPoster.equals("null")) {
				        strPoster = "";
				    }
				    if(strPoster.length()>0){
						intent = new Intent(Expositores.this, Splash2.class);
						Bundle bund = new Bundle();
						bund.putString("PUT_IMG",strPoster);
						bund.putString("PUT_PAT",strPatrocinador);
						bund.putString("PUT_TIME",strTimer);
						intent.putExtras(bund);
						startActivity(intent);
				    }
			    }
		    }
		    
			
			Resources res = getResources();
			ListView listView = (ListView) findViewById(id.list);
		    
			ExpositoresArrayAdapter adapter = new ExpositoresArrayAdapter(Expositores.this, TraeDatos, res.getString(R.string.QRY_SERVLET));
			listView.setAdapter(adapter);
				
			listView.setOnItemClickListener(new OnItemClickListener() {
				@Override
				public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
					muestra_detalle(position);
				}
			});
		}
	}

	private void muestra_detalle(int  x){
		Dictionary<String,String> dic = TraeDatos.get(x);
		String ban = dic.get("pat_idr");
		String exp = dic.get("exp_idr");
		
		if(exp != null){
			intent = new Intent(this, ExpositoresDetalle.class);
			Bundle bund = new Bundle();
			bund.putString("idexpositor",exp);
			intent.putExtras(bund);
			startActivity(intent);
		}else if(ban != null){
			intent = new Intent(this, PatrocinadoresDetalle.class);
			Bundle bund = new Bundle();
			bund.putString("idpatrocinador",ban);
			intent.putExtras(bund);
			startActivity(intent);
		}
	}
		
	public void detalle(View v){
		intent = new Intent(this, ExpositoresDetalle.class);
		startActivity(intent);
	}
	
	public void fFavoritos(View v){
		Button btnf = (Button) findViewById(R.id.iv_btn_favoritos);
		Button btnt = (Button) findViewById(R.id.iv_btn_todos);
		if (favoritos){
			btnf.setBackgroundResource(R.drawable.lst_btn_favoritos_des);
			btnt.setBackgroundResource(R.drawable.lst_btn_todos_act);
			favoritos = false;
		}else{
			btnf.setBackgroundResource(R.drawable.lst_btn_favoritos_act);	
			btnt.setBackgroundResource(R.drawable.lst_btn_todos_des);
			favoritos = true;
		}
		CargarContenido();
	}
	
	public void voidbusqueda(View v){
		buscar();
	}

	public void buscar(){
		String strBusqueda = ((EditText) Expositores.this.findViewById(id.et_buscar_buscar)).getText().toString().trim();
		if(!strBusqueda.equals(busqueda)){
			CargarContenido();
		}	
	}
	
	public void borrar(View v){
		EditText txtbusc = (EditText) Expositores.this.findViewById(id.et_buscar_buscar);
		txtbusc.setText("");
		buscar();
	}

}
